namespace CSharpPro._1103;

    public class UserServiceTest : IUserService
{
    
     private readonly List<User> _registeredUsers = new List<User>();
     
    public string Register(string username, string password, string confirmPassword)
    {
        
        if (string.IsNullOrWhiteSpace(username))
            return "注册失败：用户名不可为空";
        
        if (string.IsNullOrWhiteSpace(password))
            return "注册失败：密码不可为空";
        
        if (string.IsNullOrWhiteSpace(confirmPassword))
            return "注册失败：确认密码不可为空";
        
        if (!IsValidUsername(username))
            return "注册失败：用户名需3-15位，仅含字母、数字或下划线";
        
        if (!IsValidPassword(password))
            return "注册失败：密码需6-20位，包含大小写字母和数字";
        
        if (password != confirmPassword)
            return "注册失败：两次输入的密码不一致";
        
        if (IsUsernameExists(username))
            return "注册失败：用户名已存在";
        
        _registeredUsers.Add(new User(username, password));
        
        return "注册成功！即将返回主菜单...";
    }

    public string Login(string username, string password)
    {
        
        if (string.IsNullOrWhiteSpace(username))
            return "登录失败：用户名不可为空";
        
        if (string.IsNullOrWhiteSpace(password))
            return "登录失败：密码不可为空";
        
        foreach (var user in _registeredUsers)
        {
            if (user.Username == username)
            {
                return user.Password == password 
                    ? "登录成功！即将进入系统..." 
                    : "登录失败：密码错误";
            }
        }

        return "登录失败：用户名不存在";
    }
    
    public List<User> GetAllUsers()
    {
        return new List<User>(_registeredUsers); 
    }
    
    public bool IsUsernameExists(string username)
    {
        foreach (var user in _registeredUsers)
        {
            if (user.Username == username)
                return true;
        }
        return false;
    }
    
    private bool IsValidUsername(string username)
    {
        if (username.Length < 3 || username.Length > 15)
            return false;

        foreach (char c in username)
        {
            if (!char.IsLetterOrDigit(c) && c != '_')
                return false;
        }
        return true;
    }
    
    private bool IsValidPassword(string password)
    {
        if (password.Length < 6 || password.Length > 20)
            return false;

        bool hasUpper = false, hasLower = false, hasDigit = false;
        foreach (char c in password)
        {
            if (char.IsUpper(c)) hasUpper = true;
            if (char.IsLower(c)) hasLower = true;
            if (char.IsDigit(c)) hasDigit = true;
        }
        
        return hasUpper && hasLower && hasDigit;
    }
}
